package cn.com.twoke.easyproject.common.context.holder;

import cn.com.twoke.easyproject.common.context.UserLoginContext;
import cn.com.twoke.easyproject.common.utils.RedisUtil;
import cn.com.twoke.easyproject.modules.system.domain.SysUser;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.extra.spring.SpringUtil;

public class UserLoginContextHolder {

    private static RedisUtil redisUtil;
    private static final ThreadLocal<UserLoginContext> context = new ThreadLocal<>();

    public static void clear() {
        context.remove();
    }

    public static UserLoginContext get() {
        return context.get();
    }

    public static void set(UserLoginContext userLoginContext) {
        context.set(userLoginContext);
    }

    public static void init() {
        if (StpUtil.isLogin()) {
            if (Opt.ofNullable(redisUtil).isEmpty()){
                redisUtil = SpringUtil.getBean(RedisUtil.class);
            }
            long uid = StpUtil.getLoginIdAsLong();

            Object obj = redisUtil.get(String.format("token:login:user_info:%s", uid));
            String username = Opt.ofNullable(obj).map(UserLoginContextHolder::toSysUser)
                    .map(SysUser::getUsername).orElse("");

            UserLoginContextHolder.set(UserLoginContext.builder()
            .token(StpUtil.getTokenValue())
            .uid(uid)
            .username(username)
            .build());
        }
    }

    private static SysUser toSysUser(Object o) {
        return (SysUser) o;
    }

}
